import type { AppTypeProps } from '@/types';

import { ref, watch } from 'vue';


import _sysAppList from './app.json';

const baseUrl = import.meta.env.VITE_GLOB_API_URL;

export const sysAppList = ref<AppTypeProps[]>(_sysAppList);
export const dynamicApps = ref<AppTypeProps[]>([]);
export async function loadApps() {
  try {
    const url = `${baseUrl}/app/list`;
    const mapping = await fetch(url, {
      method: 'GET',
    });

    const res = await mapping.json();
    const { code, data } = res;
    if (code === 200 && data) {
      dynamicApps.value = data ? (data.custom as AppTypeProps[]) : [];
      if (data.system && data.system.length > 0) {
        sysAppList.value.forEach((item) => {
          const app = data.system.find(
            (app: AppTypeProps) => app.key === item.key,
          );
          if (app) {
            Object.assign(item, app);
          }
        });
      } else {
        const url = `${baseUrl}/app/savedefault`;
        fetch(url, {
          body: JSON.stringify(sysAppList.value),
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
          },
          method: 'POST',
        });
      }
    }
  } catch (error) {
    console.log(`获取app列表错误${error}`);
  }
}
loadApps();
export const appList = ref([...sysAppList.value, ...dynamicApps.value]);
watch(
  () => dynamicApps.value,
  (val) => {
    appList.value = [...sysAppList.value, ...val];
  },
  { deep: true },
);
export default {
  allAppList: appList.value,
};
